package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {


    ArrayList<Map<String, Object>> list = new ArrayList<>();

    //    private List<Map<String,Object>> aaa(){
    public AjaxController() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", "9527");
        map.put("name", "道丶诚某");
        map.put("remark", "至理宗诚信，崇高嗣法兴");
        list.add(map);
    }

    @RequestMapping("/doAjaxGet")
    public List<Map<String, Object>> doAjaxGet() {
        return list;
    }

    @RequestMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String, Object> map) {
        list.add(map);
//        return list;=========错误写法
        return "save ok";
    }


    @RequestMapping("/doAjaxDelete/{id}")
    public String doAjaxDelete(@PathVariable Integer id) {
        Iterator<Map<String, Object>> it = list.iterator();
        while (it.hasNext()) {
//            HashMap<String, Object> map = new HashMap<>();=======错误写法
//            String s = String.valueOf(id);
            Map<String, Object> map = it.next();
            if (map.get("id").equals(String.valueOf(id))) {
                it.remove();
            }
        }
        return "delete ok";
    }

    @RequestMapping("/doAjaxUpdate")
    @ResponseBody
    public String doAjaxUpdate(@RequestParam Map<String, Object> map) {
        String id = (String) map.get("id");
        Iterator<Map<String, Object>> it = list.iterator();
        Map<String,Object> obj = null;
        while (it.hasNext()) {
//            Map<String, Object> map02 = it.next();
            //-----------------
            obj = it.next();
            //--------------------
//            if (obj.get("id").equals(map.get(String.valueOf("id"))))
            if (obj.get("id").equals(map.get(id)))
                break;
//            if (map.get("id").equals(map02.get(String.valueOf("id")))){
//                map.put("name", map.get("name"));
//                map.put("remark", map.get("remark"));
//                list.add(map);
//                break;
//            }
//            obj.put("name", map.get("name"));
//            obj.put("remark", map.get("remark"));
//            list.add(map);
        }
        obj.put("name", map.get("name"));
        obj.put("remark", map.get("remark"));
        list.add(map);
        return "Update ok";
    }
}
